<template>
  <div class="relation-list" v-if="showRelations || showRelations?.length">
    <el-tabs v-if="relationList?.length" v-model="activeRelationIndex" type="border-card">
      <template v-for="(relation, i) in relationList" :key="relation.source">
        <el-tab-pane :label="relation.title" :name="i" class="layout-padding-auto">
          <RelationTable
            ref="metaTableRef"
            :relation="relation"
            :mainForm="form"
            :mainPage="page"
            :mainSource="mainSource"
            :mainData="mainData"
            :mainSelection="mainSelection"
            :isApprove="isApprove"
            :readonly="readonly || checkDisabled(relation, form)"
          />
        </el-tab-pane>
      </template>
    </el-tabs>
  </div>
</template>
<script setup>
import { computed, ref, watch } from 'vue'
import RelationTable from './RelationTable.vue'
import { checkVisible, checkDisabled } from './utils/table'

const props = defineProps({
  form: Object, // 主表行数据
  relations: Array, // relations配置
  currentOp: Object, // 当前点击的按钮
  page: Object, // 表配置
  mainSource: String, // 主表source
  mainData: Array, // 主表数据
  mainSelection: Array, // 主表选择数据
  isApprove: { type: Boolean, default: false }, // 是否审批页面
  readonly: { type: Boolean, default: false } // 是否只读，不可编辑和添加
})

const showRelations = computed(() => {
  const opRelations = props.currentOp?.relations
  if (opRelations === false || opRelations?.length === 0) {
    return false
  } else if (opRelations === true || !opRelations) {
    return true
  } else {
    return [opRelations].flat()
  }
})

const activeRelationIndex = ref(0)

const metaTableRef = ref([])

// 校验按钮配置relations
const checkShowRelation = (relation) => {
  if (typeof showRelations.value === 'boolean') {
    return showRelations.value
  }
  return showRelations.value.includes(relation.key || relation.source)
}

const relationList = computed(() =>
  props.relations.filter(
    (relation) => checkShowRelation(relation) && checkVisible(relation, props.form)
  )
)

watch(
  () => relationList.value.length,
  (val) => {
    if (activeRelationIndex.value >= val - 1) {
      activeRelationIndex.value = val < 1 ? 0 : val - 1
    }
  }
)

// 获取当前metaTableRef
const getMetaTableRef = (idx) => {
  const relation = relationList.value[idx]
  return (
    metaTableRef.value.find((xRef) => xRef.getSource() === relation.source) ||
    metaTableRef.value[idx]
  )
}

const getCurrentTableRef = () => {
  return getMetaTableRef(activeRelationIndex.value)
}

// 获取子表选择的数据
const getRelationSelections = () => {
  return relationList.value.map((relation, relationIndex) => {
    const $table = getMetaTableRef(relationIndex)?.getMetaTableRef()
    if ($table) {
      const selections = $table.getCheckboxRecords()
      return {
        ...relation,
        source: relation.source,
        selections
      }
    }
    return {
      ...relation,
      source: relation.source
    }
  })
}

// 获取修改信息
const getRelationDatas = () => {
  return relationList.value.map((relation, relationIndex) => {
    const $table = getMetaTableRef(relationIndex)?.getMetaTableRef()
    if ($table) {
      const insertList = $table.getInsertRecords()
      const removeList = $table.getRemoveRecords()
      const updateList = $table.getUpdateRecords()
      return {
        ...relation,
        source: relation.source,
        insertList,
        removeList,
        updateList,
        allList: $table.getTableData().tableData
      }
    }
    return {
      source: relation.source
    }
  })
}

// 页面关闭时，重置已修改的数据
const revertData = () => {
  relationList.value.forEach((relation, relationIndex) => {
    relation.list = []
    const $table = metaTableRef.value[relationIndex]?.tableRef
    if ($table) {
      $table.revertData()
    }
  })
}

// 初始化fields信息
const initColumns = async () => {
  relationList.value.forEach(async (relation, i) => {
    if (relation.source) {
    }
  })
}

// 可编辑表格校验必填
const editValidate = async () => {
  for (let i = 0; i < relationList.value.length; i++) {
    const $table = metaTableRef.value[i]
    if ($table) {
      const valid = await $table.editValidate()
      // 校验失败返回对象，校验成功返回undefined
      if (valid) {
        if (activeRelationIndex.value !== i) {
          activeRelationIndex.value = i
        }
        return false
      }
    }
  }
  return true
}

defineExpose({
  getRelationDatas,
  getRelationSelections,
  initColumns,
  revertData,
  editValidate,
  getCurrentTableRef
})
</script>
<style lang="less" scoped>
.relation-list {
  .relation-item {
    margin-top: 10px;
  }
  .text-btn img {
    height: 14px;
    vertical-align: middle;
    margin-right: 3px;
  }
  .relation-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 5px 0;
    .label {
      font-weight: bold;
    }
  }
}
</style>
